const BattleRoom = require('../models/BattleRoom');
const Question = require('../models/Question');
const User = require('../models/User');
const AnswerLog = require('../models/AnswerLog');
const UserProfile = require('../models/UserProfile');
const WrongQuestion = require('../models/WrongQuestion');
const QuestionCategory = require('../models/QuestionCategory');
const QuestionComment = require('../models/QuestionComment');
const { Op } = require('sequelize');
const sequelize = require('../db/db');
const { sendResponse, sendListResponse } = require('../utils/response');
const { getTimestamp, getTwoDigits, formatObject, reverseFormatObject, formatTime } = require('../utils/common');

/**
 * 创建对战房间
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const createBattleRoom = async (req, res) => {
  try {
    // 直接获取请求参数
    const { creatorId, opponentId, difficulty } = req.body;

    // 验证创建者ID是否存在
    const creator = await User.findByPk(creatorId);
    if (!creator) {
      return sendResponse(res, 500, '创建者不存在');
    }

    // 如果提供了对手ID，验证对手是否存在
    let opponent = null;
    if (opponentId) {
      opponent = await User.findByPk(opponentId);
      if (!opponent) {
        return sendResponse(res, 500, '对手不存在');
      }
    }

    // 生成房间ID: "186" + 时间戳 + 两位数随机数
    const roomId = "186" + getTimestamp() + getTwoDigits();

    // 构建题目查询条件
    const questionWhere = {
      status: 0,
      is_delete: 0
    };
    if (difficulty) {
      questionWhere.difficulty = difficulty;
    }

    // 随机获取10道题目
    const questions = await Question.findAll({
      where: questionWhere,
      order: sequelize.random(),
      limit: 10
    });

    if (questions.length < 10) {
      return sendResponse(res, 500, '可用题目数量不足');
    }

    // 获取题目ID列表
    const question_list = questions.map(q => q.id);

    // 如果没有提供对手ID，则查找带有"测试"的随机用户作为对手
    let finalOpponentId = opponentId;
    if (!opponentId) {
      const testUsers = await User.findAll({
        where: {
          nickname: {
            [Op.like]: '%测试%'
          },
          user_id: {
            [Op.ne]: creatorId // 排除创建者自己
          }
        }
      });

      if (testUsers.length > 0) {
        const randomIndex = Math.floor(Math.random() * testUsers.length);
        finalOpponentId = testUsers[randomIndex].user_id;
      }
    }

    // 创建对战房间
    const battleRoom = await BattleRoom.create({
      id: roomId,
      creator_id: creatorId,
      opponent_id: finalOpponentId,
      status: finalOpponentId ? 1 : 0, // 如果有对手则状态为对战中，否则为等待匹配
      question_list,
      start_time: finalOpponentId ? formatTime(new Date()) : null,
      creator_user_score: 0,
      opponent_user_score: 0
    });

    // 返回完整的房间信息和题目详情
    const roomWithDetails = await BattleRoom.findByPk(roomId, {
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['user_id', 'nickname']
        },
        {
          model: User,
          as: 'opponent',
          attributes: ['user_id', 'nickname']
        }
      ]
    });

    // 使用formatObject处理返回数据
    sendResponse(res, 200, '对战房间创建成功', {
      room: formatObject(roomWithDetails.toJSON()),
      questions: questions.map(q => formatObject(q.toJSON()))
    });
  } catch (error) {
    console.error('创建对战房间失败:', error);
    sendResponse(res, 500, '创建对战房间失败', error.message);
  }
};

/**
 * 提交对战答案 - 可同时提交两个用户的答案
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const submitBattleAnswer = async (req, res) => {
  try {
    // 直接获取请求参数
    const { roomId, answers } = req.body;
    // answers结构: { creator: [{questionId, answer},...], opponent: [{questionId, answer},...] }

    // 验证房间是否存在
    const room = await BattleRoom.findByPk(roomId);
    if (!room) {
      return sendResponse(res, 500, '对战房间不存在');
    }

    // 验证房间状态
    if (room.status !== 1) {
      return sendResponse(res, 500, '对战未开始或已结束');
    }

    // 获取题目列表
    const questions = await Question.findAll({
      where: {
        id: {
          [Op.in]: room.question_list
        }
      }
    });

    // 处理结果对象
    const result = {
      creator: { score: 0, wrongQuestions: [] },
      opponent: { score: 0, wrongQuestions: [] }
    };

    // 处理创建者答案
    if (answers.creator && Array.isArray(answers.creator)) {
      const { score, wrongQuestions } = await processUserAnswers(
        room.creator_id,
        answers.creator,
        questions,
        roomId,
        room.start_time
      );
      result.creator.score = score;
      result.creator.wrongQuestions = wrongQuestions;

      // 更新创建者得分
      await room.update({ creator_user_score: score });
    }

    // 处理对手答案
    if (answers.opponent && Array.isArray(answers.opponent)) {
      const { score, wrongQuestions } = await processUserAnswers(
        room.opponent_id,
        answers.opponent,
        questions,
        roomId,
        room.start_time
      );
      result.opponent.score = score;
      result.opponent.wrongQuestions = wrongQuestions;

      // 更新对手得分
      await room.update({ opponent_user_score: score });
    }

    // 重新获取房间信息，确保使用最新数据
    const updatedRoom = await BattleRoom.findByPk(roomId);

    // 如果两个用户都提交了答案，计算胜负
    if (updatedRoom.creator_user_score > 0 || updatedRoom.opponent_user_score > 0) {
      let winnerId = null;
      let isDraw = 0;

      if (updatedRoom.creator_user_score > updatedRoom.opponent_user_score) {
        winnerId = updatedRoom.creator_id;
      } else if (updatedRoom.creator_user_score < updatedRoom.opponent_user_score) {
        winnerId = updatedRoom.opponent_id;
      } else if (updatedRoom.creator_user_score > 0 && updatedRoom.creator_user_score === updatedRoom.opponent_user_score) {
        // 同分情况，算作平局，两人都是赢家
        isDraw = 1;
      }

      // 更新房间状态和结果
      await updatedRoom.update({
        status: 2,
        winner_id: winnerId,
        is_draw: isDraw, // 已修改为整数类型
        end_time: formatTime(new Date())
      });

      // 更新用户统计数据
      const totalQuestions = questions.length;

      // 更新创建者的统计数据
      await updateUserStats(updatedRoom.creator_id, updatedRoom.creator_user_score, totalQuestions);

      // 更新对手的统计数据
      await updateUserStats(updatedRoom.opponent_id, updatedRoom.opponent_user_score, totalQuestions);

      // 更新胜者的对战胜利次数
      if (winnerId) {
        const winnerProfile = await UserProfile.findOne({
          where: { user_id: winnerId }
        });
        if (winnerProfile) {
          await winnerProfile.update({
            battle_win: winnerProfile.battle_win + 1
          });
        }
      } else if (isDraw === 1) { // 修改为使用整数1表示平局
        // 如果是平局，两人都增加胜利次数
        const creatorProfile = await UserProfile.findOne({
          where: { user_id: updatedRoom.creator_id }
        });
        if (creatorProfile) {
          await creatorProfile.update({
            battle_win: creatorProfile.battle_win + 1
          });
        }

        const opponentProfile = await UserProfile.findOne({
          where: { user_id: updatedRoom.opponent_id }
        });
        if (opponentProfile) {
          await opponentProfile.update({
            battle_win: opponentProfile.battle_win + 1
          });
        }
      }

      result.isCompleted = true;
      result.winnerId = winnerId;
      result.isDraw = isDraw; // 返回是否平局的信息
    } else {
      result.isCompleted = false;
      result.winnerId = null;
      result.isDraw = 0;
    }

    // 使用formatObject处理返回数据
    sendResponse(res, 200, '答案提交成功', formatObject(result));
  } catch (error) {
    console.error('提交对战答案失败:', error);
    sendResponse(res, 500, '提交对战答案失败', error.message);
  }
};

/**
 * 更新用户统计数据的辅助函数
 * @param {String} userId - 用户ID
 * @param {Number} score - 本次得分
 * @param {Number} totalQuestions - 总题目数
 */
async function updateUserStats(userId, score, totalQuestions) {
  const userProfile = await UserProfile.findOne({
    attributes: ['id', 'user_id', 'total_question', 'total_score', 'correct_rate', 'battle_win'],
    where: { user_id: userId }
  });

  if (userProfile) {
    // 计算新的总答题数、总分数和正确率
    const totalScore = (userProfile.total_score || 0) + score;
    const totalQuestion = (userProfile.total_question || 0) + totalQuestions;

    // 确保正确率在0-100之间，并限制小数位数
    const newCorrectRate = totalQuestion > 0
      ? Math.min(100, Math.max(0, (totalScore / totalQuestion) * 100))
      : 0;

    // 更新用户统计数据
    await userProfile.update({
      total_question: totalQuestion,
      total_score: totalScore,
      correct_rate: parseFloat(newCorrectRate.toFixed(2)) // 保留两位小数
    });
  }
}

/**
 * 处理用户答案的辅助函数
 * @param {String} userId - 用户ID
 * @param {Array} userAnswers - 用户答案数组
 * @param {Array} questions - 题目数组
 * @param {String} roomId - 房间ID
 * @param {Date} startTime - 开始时间
 * @returns {Object} 处理结果
 */
async function processUserAnswers(userId, userAnswers, questions, roomId, startTime) {
  // 计算得分并记录错题
  let score = 0;
  const wrongQuestions = [];

  userAnswers.forEach(answer => {
    const question = questions.find(q => q.id === answer.questionId);
    if (question) {
      if (question.correct_key === answer.answer) {
        score++;
      } else {
        const wrongQuestionId = "190" + getTimestamp() + getTwoDigits();
        wrongQuestions.push({
          id: wrongQuestionId,
          user_id: userId,
          question_id: question.id,
          error_count: 1,
          last_wrong_time: formatTime(new Date())
        });
      }
    }
  });

  // 记录答题日志
  const answerLogId = "187" + getTimestamp() + getTwoDigits();

  // 计算答题用时（秒）- 修正时间计算逻辑
  const endTime = new Date();
  const startTimeObj = new Date(startTime);
  const totalTimeInSeconds = Math.floor((endTime - startTimeObj) / 1000);

  await AnswerLog.create({
    id: answerLogId,
    user_id: userId,
    room_id: roomId,
    answers: JSON.stringify(userAnswers),
    total_score: score,
    total_time: totalTimeInSeconds,
    mode: 2,
    create_time: formatTime(new Date())
  });

  // 记录错题
  if (wrongQuestions.length > 0) {
    for (const wrongQuestion of wrongQuestions) {
      const existing = await WrongQuestion.findOne({
        where: {
          user_id: wrongQuestion.user_id,
          question_id: wrongQuestion.question_id
        }
      });

      if (existing) {
        // 更新错题记录
        await existing.update({
          error_count: existing.error_count + 1,
          last_wrong_time: formatTime(new Date())
        });
      } else {
        // 创建新的错题记录
        await WrongQuestion.create(wrongQuestion);
      }
    }
  }

  return {
    score,
    wrongQuestions: wrongQuestions.map(q => q.question_id)
  };
}

/**
 * 获取对战结果
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const getBattleResult = async (req, res) => {
  try {
    const { id } = req.params;

    const room = await BattleRoom.findByPk(id, {
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['user_id', 'nickname']
        },
        {
          model: User,
          as: 'opponent',
          attributes: ['user_id', 'nickname'],
          required: false // 允许opponent为null（练习赛）
        }
      ]
    });

    if (!room) {
      return sendResponse(res, 500, '对战房间不存在');
    }

    // 获取创建者的答题日志
    const creatorLog = await AnswerLog.findOne({
      where: {
        room_id: room.id,
        user_id: room.creator_id
      }
    });

    // 构建基本结果对象
    const result = {
      roomId: room.id,
      creator: {
        user_id: room.creator.user_id,
        nickname: room.creator.nickname,
        score: room.creator_user_score,
        answers: creatorLog ? JSON.parse(creatorLog.answers) : null,
        total_time: creatorLog ? creatorLog.total_time : 0
      },
      winner_id: room.winner_id,
      is_draw: room.is_draw,
      start_time: room.start_time,
      end_time: room.end_time
    };

    // 如果不是练习赛，添加对手信息
    if (room.opponent_id) {
      const opponentLog = await AnswerLog.findOne({
        where: {
          room_id: room.id,
          user_id: room.opponent_id
        }
      });

      result.opponent = {
        user_id: room.opponent?.user_id,
        nickname: room.opponent?.nickname,
        score: room.opponent_user_score,
        answers: opponentLog ? JSON.parse(opponentLog.answers) : null,
        total_time: opponentLog ? opponentLog.total_time : 0
      };
    }

    sendResponse(res, 200, '获取对战结果成功', formatObject(result));
  } catch (error) {
    console.error('获取对战结果失败:', error);
    sendResponse(res, 500, '获取对战结果失败', error.message);
  }
};

/**
 * 获取排行榜
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 * @param {Object} req.query - 查询参数
 * @param {string} [req.query.type=1] - 排序类型：1-总分排行，2-正确率排行，3-对战胜场排行
 * @param {number} [req.query.page=1] - 页码
 * @param {number} [req.query.pageSize=10] - 每页条数
 */
const getRankingList = async (req, res) => {
  try {
    // 直接获取请求参数
    const { type = '1', page = 1, pageSize = 10 } = req.query;

    // 验证排序类型
    const validTypes = ['1', '2', '3'];
    if (!validTypes.includes(type)) {
      return sendResponse(res, 500, '无效的排序类型');
    }

    // 获取对应的数据库字段
    const typeFieldMap = {
      '1': 'total_score',
      '2': 'correct_rate',
      '3': 'battle_win'
    };

    const orderField = typeFieldMap[type];

    // 计算偏移量
    const offset = (page - 1) * pageSize;

    // 获取排行榜数据
    const rankingList = await UserProfile.findAll({
      attributes: ['id', 'user_id', 'total_question', 'total_score', 'correct_rate', 'battle_win'],
      include: [{
        model: User,
        attributes: ['user_id', 'nickname']
      }],
      order: [[orderField, 'DESC']],
      limit: parseInt(pageSize),
      offset: parseInt(offset)
    });

    // 获取总记录数
    const total = await UserProfile.count();

    // 格式化返回数据
    const formattedList = rankingList.map((profile, index) => {
      return formatObject({
        rank: offset + index + 1,
        userId: profile.user_id,
        nickname: profile.User.nickname,
        totalQuestion: profile.total_question,
        totalScore: profile.total_score,
        correctRate: profile.correct_rate,
        battleWin: profile.battle_win
      });
    });

    sendListResponse(res, 200, '获取排行榜成功', formatObject(formattedList), total);
  } catch (error) {
    console.error('获取排行榜失败:', error);
    sendResponse(res, 500, '获取排行榜失败', error.message);
  }
};

/**
 * 获取用户排名
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 * @param {Object} req.query - 查询参数
 * @param {string} req.query.userId - 用户ID
 * @param {string} [req.query.type=1] - 排序类型：1-总分排行，2-正确率排行，3-对战胜场排行
 */
const getUserRank = async (req, res) => {
  try {
    // 直接获取请求参数
    const { userId, type = '1' } = req.query;

    // 验证排序类型
    const validTypes = ['1', '2', '3'];
    if (!validTypes.includes(type)) {
      return sendResponse(res, 500, '无效的排序类型');
    }

    // 获取对应的数据库字段
    const typeFieldMap = {
      '1': 'total_score',
      '2': 'correct_rate',
      '3': 'battle_win'
    };

    const orderField = typeFieldMap[type];

    // 获取用户数据
    const userProfile = await UserProfile.findOne({
      attributes: ['id', 'user_id', 'total_question', 'total_score', 'correct_rate', 'battle_win'],
      where: { user_id: userId },
      include: [{
        model: User,
        attributes: ['user_id', 'nickname', "create_time"]
      }]
    });

    if (!userProfile) {
      return sendResponse(res, 500, '用户不存在');
    }

    // 获取用户排名
    const rank = await UserProfile.count({
      where: {
        [orderField]: {
          [Op.gt]: userProfile[orderField]
        }
      }
    }) + 1;

    // 获取总用户数
    const total = await UserProfile.count();

    // 构建并格式化返回结果
    const result = {
      rank,
      total,
      user: {
        userId: userProfile.user_id,
        nickname: userProfile.User.nickname,
        totalQuestion: userProfile.total_question,
        totalScore: userProfile.total_score,
        correctRate: userProfile.correct_rate,
        battleWin: userProfile.battle_win,
        createTime: userProfile.User.create_time,
      }
    };

    sendResponse(res, 200, '获取用户排名成功', formatObject(result));
  } catch (error) {
    console.error('获取用户排名失败:', error);
    sendResponse(res, 500, '获取用户排名失败', error.message);
  }
};

/**
 * 创建练习赛
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const createPractice = async (req, res) => {
  try {
    // 直接获取请求参数
    const { userId, difficulty } = req.body;

    // 验证用户是否存在
    const user = await User.findByPk(userId);
    if (!user) {
      return sendResponse(res, 500, '用户不存在');
    }

    // 生成房间ID: "186" + 时间戳 + 两位数随机数
    const roomId = "186" + getTimestamp() + getTwoDigits();

    // 构建题目查询条件
    const questionWhere = {
      status: 0,
      is_delete: 0
    };
    if (difficulty) {
      questionWhere.difficulty = difficulty;
    }

    // 随机获取10道题目
    const questions = await Question.findAll({
      where: questionWhere,
      order: sequelize.random(),
      limit: 10
    });

    if (questions.length < 10) {
      return sendResponse(res, 500, '可用题目数量不足');
    }

    // 获取题目ID列表
    const question_list = questions.map(q => q.id);

    // 创建练习房间
    const practiceRoom = await BattleRoom.create({
      id: roomId,
      creator_id: userId,
      status: 1, // 直接开始
      question_list,
      start_time: formatTime(new Date()),
      creator_user_score: 0
    });

    // 使用formatObject处理返回数据
    sendResponse(res, 200, '练习赛创建成功', formatObject({
      roomId: practiceRoom.id,
      questions: questions.map(q => formatObject(q.toJSON()))
    }));
  } catch (error) {
    console.error('创建练习赛失败:', error);
    sendResponse(res, 500, '创建练习赛失败', error.message);
  }
};

/**
 * 提交练习赛答案
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 * @param {Object} req.body - 请求体
 * @param {string} req.body.roomId - 房间ID
 * @param {string} req.body.userId - 用户ID
 * @param {Array} req.body.answers - 答案数组，格式：[{questionId: string, answer: string}]
 */
const submitPracticeAnswer = async (req, res) => {
  try {
    // 直接获取请求参数
    const { roomId, userId, answers } = req.body;

    // 验证房间是否存在
    const room = await BattleRoom.findByPk(roomId);
    if (!room) {
      return sendResponse(res, 500, '练习房间不存在');
    }

    // 验证用户是否是房间的创建者
    if (userId !== room.creator_id) {
      return sendResponse(res, 500, '你不是该房间的创建者');
    }

    // 验证房间状态
    if (room.status !== 1) {
      return sendResponse(res, 500, '练习未开始或已结束');
    }

    // 验证answers格式
    if (!Array.isArray(answers) || answers.length === 0) {
      return sendResponse(res, 500, '答案格式不正确');
    }

    // 获取题目列表
    const questions = await Question.findAll({
      where: {
        id: {
          [Op.in]: room.question_list
        }
      }
    });

    // 计算得分并记录错题
    let score = 0;
    const wrongQuestions = [];

    answers.forEach(answer => {
      const question = questions.find(q => q.id === answer.questionId);
      if (question) {
        if (question.correct_key === answer.answer) {
          score++;
        } else {
          const wrongQuestionId = "190" + getTimestamp() + getTwoDigits();
          wrongQuestions.push({
            id: wrongQuestionId,
            user_id: userId,
            question_id: question.id,
            error_count: 1,
            last_wrong_time: formatTime(new Date())
          });
        }
      }
    });

    // 更新用户得分
    await room.update({
      creator_user_score: score,
      status: 2,
      end_time: formatTime(new Date())
    });

    // 记录答题日志
    const answerLogId = "187" + getTimestamp() + getTwoDigits();

    // 计算答题用时（秒）- 修正时间计算逻辑
    const endTime = new Date();
    const startTimeObj = new Date(room.start_time);
    const totalTimeInSeconds = Math.floor((endTime - startTimeObj) / 1000);

    await AnswerLog.create({
      id: answerLogId,
      user_id: userId,
      room_id: room.id,
      answers: JSON.stringify(answers),
      total_score: score,
      total_time: totalTimeInSeconds,
      mode: 1, // 1-练习模式
      create_time: formatTime(new Date())
    });

    // 记录错题
    if (wrongQuestions.length > 0) {
      for (const wrongQuestion of wrongQuestions) {
        const existing = await WrongQuestion.findOne({
          where: {
            user_id: wrongQuestion.user_id,
            question_id: wrongQuestion.question_id
          }
        });

        if (existing) {
          // 更新错题记录
          await existing.update({
            error_count: existing.error_count + 1,
            last_wrong_time: formatTime(new Date())
          });
        } else {
          // 创建新的错题记录
          await WrongQuestion.create(wrongQuestion);
        }
      }
    }

    // 更新用户统计数据
    const userProfile = await UserProfile.findOne({
      where: { user_id: userId }
    });


    if (userProfile) {
      const totalQuestions = questions.length;
      const newTotalQuestion = userProfile.total_question + totalQuestions
      const newTotalScore = userProfile.total_score + score
      const newCorrectRate = (newTotalScore / newTotalQuestion) * 100;


      await userProfile.update({
        total_question: newTotalQuestion,
        total_score: newTotalScore,
        correct_rate: parseFloat(newCorrectRate.toFixed(2))
      });
    }

    // 使用formatObject处理返回数据
    sendResponse(res, 200, '练习赛答案提交成功', formatObject({
      score,
      total_questions: questions.length,
      wrong_questions: wrongQuestions.map(q => q.question_id)
    }));
  } catch (error) {
    console.error('提交练习赛答案失败:', error);
    sendResponse(res, 500, '提交练习赛答案失败', error.message);
  }
};

/**
 * 获取房间题目列表
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const getRoomQuestions = async (req, res) => {
  try {
    const { roomId } = req.params;

    // 查找房间
    const room = await BattleRoom.findByPk(roomId);

    // 检查房间是否存在
    if (!room) {
      return sendResponse(res, 400, '房间不存在');
    }

    // 获取题目列表，包含创建者信息和分类信息，添加评分信息
    const questions = await Question.findAll({
      where: {
        id: {
          [Op.in]: room.question_list
        }
      },
      attributes: [
        'id', 'content', 'options', 'difficulty', 'category_id',
        'create_time', 'user_id', "correct_key",
        'user_rated_difficulty', 'user_rated_quality', 'rating_count'
      ],
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['nickname'],
          required: false
        },
        {
          model: QuestionCategory,
          as: 'category',
          attributes: ['name'],
          required: false
        }
      ]
    });

    // 获取题目的评论数量
    const questionIds = questions.map(q => q.id);

    // 查询每个题目的评论数量
    const commentCounts = await QuestionComment.findAll({
      attributes: [
        'question_id',
        [sequelize.fn('COUNT', sequelize.col('id')), 'comment_count']
      ],
      where: {
        question_id: {
          [Op.in]: questionIds
        },
      },
      group: ['question_id'],
      raw: true
    });

    // 将评论数量映射为对象
    const commentMap = {};
    commentCounts.forEach(item => {
      commentMap[item.question_id] = parseInt(item.comment_count);
    });

    // 格式化并返回题目列表
    const formattedQuestions = questions.map(question => {
      const questionData = question.toJSON();
      return formatObject({
        ...questionData,
        creatorName: questionData.creator?.nickname || '',
        categoryName: questionData.category?.name || '',
        commentCount: commentMap[questionData.id] || 0,
        userRatedDifficulty: parseFloat(questionData.user_rated_difficulty) || 0,
        userRatedQuality: parseFloat(questionData.user_rated_quality) || 0
      });
    });

    sendListResponse(res, 200, '获取题目列表成功', formattedQuestions, 10);
  } catch (error) {
    console.error('获取房间题目列表失败:', error);
    sendResponse(res, 500, '获取房间题目列表失败', error.message);
  }
};

/**
 * 获取用户对战历史
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 * @param {Object} req.query - 查询参数
 * @param {string} req.query.userId - 用户ID
 * @param {number} [req.query.page=1] - 页码
 * @param {number} [req.query.pageSize=10] - 每页条数
 * @param {number} [req.query.type] - 对战类型：1-练习赛，2-对战赛，不传则查询所有
 */
const getUserBattleHistory = async (req, res) => {
  try {
    const { userId, page = 1, pageSize = 10, type } = req.query;

    // 计算偏移量
    const offset = (parseInt(page) - 1) * parseInt(pageSize);

    // 构建查询条件
    const whereCondition = {
      status: 2, // 只查询已结束的
    };

    // 根据类型筛选：1-练习赛，2-对战赛
    if (type === '1') {
      // 练习赛：用户是创建者且没有对手
      whereCondition.creator_id = userId;
      whereCondition.opponent_id = null;
    } else if (type === '2') {
      // 对战赛：用户是创建者或对手，且有对手
      whereCondition[Op.and] = [
        {
          [Op.or]: [
            { creator_id: userId },
            { opponent_id: userId }
          ]
        },
        {
          opponent_id: {
            [Op.ne]: null
          }
        }
      ];
    } else {
      // 不指定类型时，查询所有
      whereCondition[Op.or] = [
        { creator_id: userId },
        { opponent_id: userId }
      ];
    }

    // 查询用户参与的对战
    const { count, rows } = await BattleRoom.findAndCountAll({
      where: whereCondition,
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['user_id', 'nickname']
        },
        {
          model: User,
          as: 'opponent',
          attributes: ['user_id', 'nickname']
        }
      ],
      order: [['end_time', 'DESC']], // 按结束时间倒序排序
      limit: parseInt(pageSize),
      offset: offset
    });

    // 格式化对战记录
    const battleHistory = rows.map(room => {
      const roomData = room.toJSON();
      const isCreator = roomData.creator_id === userId;
      const isPractice = !roomData.opponent_id;

      return formatObject({
        roomId: roomData.id,
        startTime: roomData.start_time,
        endTime: roomData.end_time,
        type: isPractice ? 1 : 2, // 1-练习赛，2-对战赛
        // 当前用户信息
        userInfo: {
          userId: userId,
          nickname: isCreator ? roomData.creator?.nickname : roomData.opponent?.nickname,
          score: isCreator ? roomData.creator_user_score : roomData.opponent_user_score
        },
        // 对手信息（练习赛时为null）
        opponentInfo: isPractice ? null : {
          userId: isCreator ? roomData.opponent_id : roomData.creator_id,
          nickname: isCreator ? roomData.opponent?.nickname : roomData.creator?.nickname,
          score: isCreator ? roomData.opponent_user_score : roomData.creator_user_score
        },
        isDraw: roomData.is_draw === 1,
        isWin: isPractice ? null : roomData.winner_id === userId
      });
    });

    sendListResponse(res, 200, '获取对战历史成功', battleHistory, count);
  } catch (error) {
    console.error('获取用户对战历史失败:', error);
    sendResponse(res, 500, '获取用户对战历史失败', error.message);
  }
};

/**
 * 获取对战房间列表
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 * @param {Object} req.query - 查询参数
 * @param {number} [req.query.page=1] - 页码
 * @param {number} [req.query.pageSize=10] - 每页条数
 */
const getBattleRoomList = async (req, res) => {
  try {
    const { page = 1, pageSize = 10 } = req.query;

    // 计算偏移量
    const offset = (parseInt(page) - 1) * parseInt(pageSize);

    // 查询对战房间列表 - 不添加任何条件
    const { count, rows } = await BattleRoom.findAndCountAll({
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['user_id', 'nickname']
        },
        {
          model: User,
          as: 'opponent',
          attributes: ['user_id', 'nickname'],
          required: false // 允许opponent为null的情况
        }
      ],
      order: [
        ['create_time', 'DESC']  // 按创建时间倒序排序
      ],
      limit: parseInt(pageSize),
      offset: offset
    });

    // 格式化房间列表
    const roomList = rows.map(room => {
      const roomData = room.toJSON();
      const isPractice = !roomData.opponent_id;
      const formattedRoom = formatObject({
        roomId: roomData.id,
        creatorId: roomData.creator_id,
        creatorName: roomData.creator?.nickname || '未知用户',
        opponentId: roomData.opponent_id,
        opponentName: roomData.opponent?.nickname || '无对手',
        status: roomData.status,
        statusText: getStatusText(roomData.status),
        isPractice,
        startTime: roomData.start_time,
        endTime: roomData.end_time,
        creatorScore: roomData.creator_user_score,
        opponentScore: roomData.opponent_user_score,
        isDraw: roomData.is_draw === 1,
        winnerId: roomData.winner_id,
        winnerName: getWinnerName(roomData),
        createTime: roomData.create_time,
        questionCount: Array.isArray(roomData.question_list) ? roomData.question_list.length : 0
      });

      return formattedRoom;
    });

    sendListResponse(res, 200, '获取对战房间列表成功', roomList, count);
  } catch (error) {
    console.error('获取对战房间列表失败:', error);
    sendResponse(res, 500, '获取对战房间列表失败', error.message);
  }
};

/**
 * 获取房间状态文本
 * @param {number} status - 房间状态
 * @returns {string} 状态文本
 */
function getStatusText(status) {
  switch (status) {
    case 0:
      return '等待匹配';
    case 1:
      return '对战中';
    case 2:
      return '已结束';
    default:
      return '未知状态';
  }
}

/**
 * 获取获胜者名称
 * @param {Object} room - 房间数据
 * @returns {string} 获胜者名称
 */
function getWinnerName(room) {
  if (room.is_draw === 1) {
    return '平局';
  }

  if (!room.winner_id) {
    return '无胜者';
  }

  if (room.winner_id === room.creator_id) {
    return room.creator?.nickname || '未知用户';
  }

  return room.opponent?.nickname || '未知用户';
}

module.exports = {
  createBattleRoom,
  submitBattleAnswer,
  getBattleResult,
  getRankingList,
  getUserRank,
  createPractice,
  submitPracticeAnswer,
  getRoomQuestions,
  getUserBattleHistory,
  getBattleRoomList
}; 